package com.ejlchina.tool.fragment

import android.annotation.SuppressLint
import android.app.DownloadManager
import android.content.Context
import android.os.Bundle
import android.os.Environment
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.adolf.androiddemo.R
import com.adolf.androiddemo.databinding.FragmentFirmwareUpgradeBinding
import com.ejlchina.tool.MainActivity
import com.ejlchina.tool.adapter.DeviceHeadAdapterMulti
import com.ejlchina.tool.adapter.DeviceHeadAdapterRadio
import com.ejlchina.tool.adapter.FirmwareVersionAdapter
import com.ejlchina.tool.base.BaseBindingFragment2
import com.ejlchina.tool.bean.BleDeviceBean
import com.ejlchina.tool.bean.IndicatorDataBean
import com.ejlchina.tool.constant.DEVICE_MODE_OFFLINE
import com.ejlchina.tool.enums.UpgradeStateEnum
import com.ejlchina.tool.extension.safeNavigate
import com.ejlchina.tool.network.NetApi
import com.ejlchina.tool.network.RemoteCtrlBoardVersion
import com.ejlchina.tool.singleton.GlobalAction
import com.ejlchina.tool.singleton.GlobalConnectObject
import com.ejlchina.tool.singleton.GlobalParams
import com.ejlchina.tool.util.COMMAND_FIRMWARE_VERSION_DOWNWARD
import com.ejlchina.tool.util.COMMAND_FIRMWARE_VERSION_UPWARD
import com.ejlchina.tool.util.DeviceUtil
import com.ejlchina.tool.util.DownloadUtil
import com.ejlchina.tool.util.LOG_TAG
import com.ejlchina.tool.util.bytearray.toHexString
import com.ejlchina.tool.util.deleteFile
import com.ejlchina.tool.util.getDownwardCommand
import com.ejlchina.tool.util.getUpwardData
import com.ejlchina.tool.util.getVersionNo
import com.ejlchina.tool.util.removeSpecifiedDeviceInList
import com.ejlchina.tool.util.showToast
import com.ejlchina.tool.view.GridItemDecoration
import com.ejlchina.tool.viewmodel.MainViewModel
import com.huyuhui.fastble.BleManager
import com.huyuhui.fastble.data.BleDevice
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import java.io.File

class FirmwareUpgradeFragment: BaseBindingFragment2<FragmentFirmwareUpgradeBinding>() {

    private val firmwareVersionList = mutableListOf<RemoteCtrlBoardVersion>()
    private lateinit var firmwareVersionAdapter: FirmwareVersionAdapter
    private lateinit var downloadManager: DownloadManager
    private val viewModel: MainViewModel by viewModels()



    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initViews()
        initListeners()
        initData()
        initObservers()
    }


    private fun initViews(){
        setHeadTitle("固件升级")
        setRightIconVisibility(View.GONE)    }

    private fun initListeners(){

        binding.tvUpgradeProgress.setOnClickListener {
            GlobalParams.firmwareUpgradeList.removeIf { it.upgradeResult >= 100 || it.upgradeResult < 0 }
            if (GlobalParams.firmwareUpgradeList.isNotEmpty()){
                findNavController().safeNavigate(R.id.action_firmware_to_progress_dialog)
            } else {
                showToast("没有升级项目")
            }

        }
    }

    @SuppressLint("UnspecifiedRegisterReceiverFlag")
    private fun initData(){
        downloadManager = requireContext().getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
        initDevices()
        initVersionData()
        getVersion()
    }

    private fun initObservers() {
        viewLifecycleOwner.lifecycleScope.launch {
            launch {
                IntRange(1, Int.MAX_VALUE).asFlow().collect {
                    val result =
                        if (GlobalParams.firmwareUpgradeList.size > 0
                            && !GlobalParams.isAllDeviceUpgradeComplete()) UpgradeStateEnum.UPGRADE_DISABLE else UpgradeStateEnum.UPGRADE_ENABLE
                    delay(1000)
                    firmwareVersionAdapter.isItemDisable(result)
                    firmwareVersionAdapter.notifyDataSetChanged()

                }
            }
        }
    }

    override fun whenDeviceDisConnect(disConnectDevice: BleDevice) {
        super.whenDeviceDisConnect(disConnectDevice)
        if (GlobalConnectObject.getCurrentConnectDeviceList().isNotEmpty()){
            GlobalConnectObject.getCurrentConnectDeviceList()[0].isSelect = true
        }
        deviceListHeadAdapterMulti.notifyDataSetChanged()
    }



    private fun getVersion(){
        showLoading()
        NetApi.availableVersions(GlobalConnectObject.getCurrentConnectDeviceList()[0].hardVersion){
            viewLifecycleOwner.lifecycleScope.launch{
                firmwareVersionList.clear()
                firmwareVersionList.addAll(it)
                firmwareVersionAdapter.notifyDataSetChanged()
                dismissLoading()
            }
        }
    }

    private fun initVersionData(){
        firmwareVersionAdapter = FirmwareVersionAdapter(firmwareVersionList){ remoteCtrlBoardVersion ->
            if (GlobalConnectObject.getCurrentConnectDeviceList().size > 0){
                addSelectDeviceToUpgradeList(remoteCtrlBoardVersion.verNo)
                GlobalAction.getFirmwareUpdateFlows()
                viewLifecycleOwner.lifecycleScope.launch(Dispatchers.IO) {
                    deleteFile(requireContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS))
                    delay(400)
                    downloadVersionFile(remoteCtrlBoardVersion)
//                    (requireActivity() as MainActivity).handleUpgrade()
                }
                GlobalParams.firmwareUpgradeList.removeIf { it.upgradeResult >= 100 || it.upgradeResult < 0 }
                findNavController().safeNavigate(R.id.action_firmware_to_progress_dialog)
            } else {
                showToast("还没有连接设备")
            }
        }
        firmwareVersionAdapter.isItemDisable(isSelectDeviceSameAsUpgradeList())
        binding.rvVersion.apply {
            adapter = firmwareVersionAdapter
            layoutManager = LinearLayoutManager(requireContext())
        }
    }

    private fun addSelectDeviceToUpgradeList(verNo: String){
        Log.i(LOG_TAG,"*****************************${deviceListHeadAdapterMulti.getSelectDeviceList().size}")
        for (item in deviceListHeadAdapterMulti.getSelectDeviceList()){
            if (!GlobalParams.isDeviceInUpgrade(item.bleDevice.mac)){
                GlobalParams.firmwareUpgradeList.add(item.apply {
                    upgradeToVersion = verNo
                    upgradeResult = 0F
                })
            }
        }
    }

    private fun downloadVersionFile(remoteCtrlBoardVersion: RemoteCtrlBoardVersion){
//        val file = File( requireContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS),"${remoteCtrlBoardVersion.verNo}.bin")
        val downloadUtil = DownloadUtil(requireContext())
        (activity as MainActivity).firmwareDownloadId = downloadUtil.downloadFirmware(remoteCtrlBoardVersion,downloadManager)
    }

    private fun initDevices(){
        GlobalConnectObject.getCurrentConnectDeviceList().forEach { it.isSelect = GlobalParams.isDeviceInFirmwareUpgrade(it.bleDevice.mac) }
        if (checkDeviceMode() == DEVICE_MODE_OFFLINE){
            GlobalConnectObject.getCurrentConnectDeviceList().forEachIndexed { index, bleDeviceBean -> bleDeviceBean.indexInOffline = index + 1 }
        }
//        firmwareUpgradeList.addAll(BleManager.getAllConnectedDevice().map { bleDevice ->  BleDeviceBean(bleDevice, isSelect = GlobalParams.isDeviceInFirmwareUpgrade(bleDevice.mac)) })
        deviceListHeadAdapterMulti = DeviceHeadAdapterMulti(GlobalConnectObject.getCurrentConnectDeviceList())
        binding.rvDevices.apply {
            adapter = deviceListHeadAdapterMulti
            layoutManager = GridLayoutManager(requireContext(),2)
            if (itemDecorationCount == 0){
                addItemDecoration(GridItemDecoration(2,11,11))
            }
        }
    }

    private fun handleDeviceItemClick(bleDeviceBean: BleDeviceBean){
        firmwareVersionAdapter.isItemDisable(isSelectDeviceSameAsUpgradeList())
    }

    private fun isSelectDeviceSameAsUpgradeList(): UpgradeStateEnum {
        val selectList = deviceListHeadAdapterMulti.getSelectDeviceList()
        if (selectList.isEmpty()) return UpgradeStateEnum.NO_UPGRADE
        val upgradeListMac = GlobalParams.firmwareUpgradeList.filter { it.upgradeResult > 0 && it.upgradeResult < 100 }.map { it.bleDevice.mac }
        if (upgradeListMac.isEmpty()) return UpgradeStateEnum.UPGRADE_ENABLE
        if (selectList.size > GlobalParams.firmwareUpgradeList.size) return UpgradeStateEnum.UPGRADE_ENABLE
        for (item in selectList){
            if (!upgradeListMac.contains(item.bleDevice.mac)){
                return UpgradeStateEnum.UPGRADE_ENABLE
            }
        }
        return UpgradeStateEnum.UPGRADE_DISABLE
    }

    override fun getViewBinding(inflater: LayoutInflater, container: ViewGroup): FragmentFirmwareUpgradeBinding {
        return FragmentFirmwareUpgradeBinding.inflate(inflater,container,true)
    }

    override fun onResume() {
        super.onResume()
        GlobalParams.firmwareUpgradeList.removeIf { it.upgradeResult >= 100 || it.upgradeResult < 0 }
        GlobalParams.firmwareUpgradeList.removeIf { localConnectBean ->
            !viewModelActivity.getAllConnectDevices().map { it.mac }.contains(localConnectBean.bleDevice.mac)
        }
        if (GlobalParams.firmwareUpgradeList.isEmpty()){
            firmwareVersionAdapter.isItemDisable(UpgradeStateEnum.UPGRADE_ENABLE)
        }
    }
}